/*
 *  Copyright (C), 2015-2024
 *  FileName: custom_lock
 *  Author: Tonight丶相拥
 *  Date: 5/21/24
 *  Description: 
 **/
part of 'flutter_tool.dart';

enum CustomLockStatus {
  lock('锁定', 'lock'),
  unlock('解锁', 'unlock'),
  prepare('就绪', 'prepare');
  const CustomLockStatus(this.description, this.rawValue);
  /// 状态描述
  final String description;
  /// 真实值
  final String rawValue;

  @override
  String toString(){
    return 'CustomLockStatus(description: $description, rawValue: $rawValue)';
  }
}

class CustomLock<T> {
  /// 锁
  Future<T>? _lock;
  Completer<T>? _completer;
  /// 状态
  CustomLockStatus _status = CustomLockStatus.prepare;
  /// 是否处于锁定
  bool get isLocking => _status == CustomLockStatus.lock;
  /// 锁状态
  CustomLockStatus get lockStatus => _status;
  /// 是否初始化锁
  bool get isInitLock => _lock != null;

  /// 初始化锁
  void _initializeLock() {
    _completer = Completer();
    _lock = null;
    _status = CustomLockStatus.prepare;
  }

  /// 等待锁返回
  Future<T> awaitLockResult() async{
    return await _lock!;
  }

  /// 锁定
  void lock() async{
    _initializeLock();
    _lock = _completer?.future;
    _status = CustomLockStatus.lock;
  }

  /// 解锁
  void unlock([T? value]){
    _completer?.complete(value);
    _status = CustomLockStatus.unlock;
  }
}